%% estimaStates 
% 
%
cd(cucd); 

%% 1. Kalman filter and State decomposition 
[KFStru,logL]=feval(addsol.funcKfilter,parMode,funcmod,Y,trainvec,solveopt,addsol); 

cd(outpath); 
save workspace; 
cd(cucd); 


%% 7. Table with States and Innovations in Filter 
cd(outpath);
if isunix==0
    xlswrite('Filter',crtcell(corrcoef(KFStru.innovations),shockNames,shockNames,...
        {'Correlation'}),'correlation Innovations');
    xlswrite('Filter',crtcell(KFStru.filteredSt,sampleSS.sampleCell,nameStru.stateNames,...
        {'Smooth States'}),'filtered States');
        xlswrite('Filter',crtcell(KFStru.smoothSt,sampleSS.sampleCell,nameStru.stateNames,...
        {'Smooth States'}),'smooth States');

    xlswrite('Filter',crtcell(KFStru.innovations,sampleSS.sampleCell,nameStru.shockNames,...
        {'Smooth Innovations'}),'innovations');
else 
    savecell( crtcell(corrcoef(KFStru.innovations),shockNames,shockNames,...
        {'Correlation'}),[],outpath,'Filter Correlation'); 
    savecell( crtcell(KFStru.smoothSt,sampleSS.sampleCell,nameStru.stateNames,...
        {'Smooth States'}),[],outpath,'Filter States'); 
    savecell(crtcell(KFStru.innovations,sampleSS.sampleCell,nameStru.shockNames,...
        {'Smooth Innovations'}),[],outpath,'Filter Innovations');
end 

cd(cucd);
disp('Turn me into a TEX Table');



%% 2. Decomposition for the Observables 

%% 2.a Grouped by Observables, that shock Only
clear inStru
inStru.caseDecomp='single'; 
inStru.orgBy='series'; 
graphMat=DecompSeries(Y,funcmod,parMode,solveopt,addsol,inStru,KFStru,sampleSS,[],nameStru); 
compileGraphsPDF(graphMat,'Obs Dec by Series',outpath); 
close all; 

%% 2.b Grouped by Shocks, that shock Only 
inStru.caseDecomp='single'; 
inStru.orgBy='shocks'; 
graphMat=DecompSeries(Y,funcmod,parMode,solveopt,addsol,inStru,KFStru,sampleSS,[],nameStru); 
compileGraphsPDF(graphMat,'Obs Dec by Shocks',outpath); 
close all; 

%% 2.c Excluding that Shock 
inStru.caseDecomp='except'; 
inStru.orgBy='shocks'; 
graphMat=DecompSeries(Y,funcmod,parMode,solveopt,addsol,inStru,KFStru,sampleSS,[],nameStru); 
compileGraphsPDF(graphMat,'Obs Dec Except',outpath); 
close all; 

%% 2.d Contribution of Shocks 
clear inStru
inStru.caseDecomp='single';
inStru.orgBy='shocks';
inStru.extract=nameStru.obsNames;
graphMat=shockContributions(inStru,KFStru,sampleSS,[],nameStru);
compileGraphsPDF(graphMat,'Obs Contrib',outpath);
close all; 

%% 3.Decomposition for states, grouped by Observables
if flagStru.stateDecomp==true    
    %% 3.a Grouped by Observables, that shock Only
    clear inStru
    inStru.caseDecomp='single';
    inStru.orgBy='series';
    inStru.extract=report.stateDecomp; 
    graphMat=DecompSeries([],funcmod,parMode,solveopt,addsol,inStru,KFStru,sampleSS,[],nameStru);
    compileGraphsPDF(graphMat,'States Dec by Series',outpath);
    close all;
    %% 3.b Excluding that Shock 
    inStru.caseDecomp='except';
    inStru.orgBy='shocks';
    graphMat=DecompSeries([],funcmod,parMode,solveopt,addsol,inStru,KFStru,sampleSS,[],nameStru);
    compileGraphsPDF(graphMat,'State Dec Except',outpath);
    close all; 
    %% 3.c Contribution of Shocks 
    inStru.caseDecomp='single';
    inStru.orgBy='shocks';
        inStru.extract=report.stateDecomp; 

    graphMat=shockContributions(inStru,KFStru,sampleSS,[],nameStru);
    compileGraphsPDF(graphMat,'State Contrib',outpath);
    close all;
end 

%% 4. Plot of Innovations 
nameStru.colNames=shockNames; 
clear graphStru; 
graphStru.suptitle='Innovations'; 
graphStru.subtitle=outpath; 
graphStru.subtitleFontSize=9; 
handlesInnovations=plotStates(KFStru.innovations,sampleSS,graphStru,nameStru); 
compileGraphsPDF(handlesInnovations,'Innovations',outpath); 
clear graphStru handlesInnovations; 

%% 5. Plot of Selected States 
if flagStru.stateDecomp==true 
    clear graphStru;
    graphStru.suptitle='Smooth States';
    graphStru.subtitle=[];
    graphStru.subtitleFontSize=9;
    %graphStru.extract=report.stateDecomp; 
    nameStru.colNames=report.stateDecomp;
    tempMat=KFStru.smoothSt(:,report.stateDecompPos);
    handlesStates=plotStates(tempMat,sampleSS,graphStru,nameStru);
    compileGraphsPDF(handlesStates,'States',outpath); 
    clear graphStru handlesStates;
end 

%% 6. Decomposition of observables for selected subsamples
if flagStru.subSamples==1;
    NSub=size(report.subSamples,1);
    clear inStru
    inStru.caseDecomp='single';
    for ii=1:NSub
        tempPos=(report.subSamplePos(ii,1):report.subSamplePos(ii,2));
        tempKFStru.countObs=KFStru.countObs(tempPos,:,:);
        tempKFStru.countSt=KFStru.countSt(tempPos,:,:);

        tempSampleStru.sampleVec=sampleSS.sampleVec(tempPos);
        tempString={[char(report.subSamples(ii,1)),' ',char(report.subSamples(ii,2))]};
        tempString=regexprep(tempString,'-','_');
        %% 6.a Grouped by Observables, that shock Only
        inStru.orgBy='series';
        inStru.caseDecomp='single';
        graphMat=DecompSeries(Y(tempPos,:),funcmod,parMode,solveopt,addsol,...
            inStru,tempKFStru,tempSampleStru,[],nameStru);
        tempFileName=['Obs Dec ',char(tempString)];
        compileGraphsPDF(graphMat,tempFileName,outpath);
        clear graphMat
        close all;
        %% 6.b Exclude, by Shocks 
        inStru.orgBy='shocks';
        inStru.caseDecomp='except';
        graphMat=DecompSeries(Y(tempPos,:),funcmod,parMode,solveopt,addsol,...
            inStru,tempKFStru,tempSampleStru,[],nameStru);
        tempFileName=['Obs Except ',char(tempString)];
        compileGraphsPDF(graphMat,tempFileName,outpath);
        clear graphMat
        close all;
        %% 6.c Contributions

        inStru.caseDecomp='single';
        inStru.orgBy='shocks';
        inStru.extract=nameStru.obsNames;
        graphMat=shockContributions(inStru,tempKFStru,tempSampleStru,[],nameStru);
        tempFileName=['Obs Contrib ',char(tempString)];
        compileGraphsPDF(graphMat,tempFileName,outpath);
        
        %%
        if flagStru.stateDecomp==true
           %% 6.d Grouped by States, that shock Only          
           inStru.caseDecomp='single';
           inStru.orgBy='series';
           inStru.extract=report.stateDecomp;
           tempKFStru.countSt=KFStru.countSt(tempPos,:,:);
           tempFileName=['States Dec ',char(tempString)];
           graphMat=DecompSeries([],funcmod,parMode,solveopt,addsol,inStru,tempKFStru,...
               tempSampleStru,[],nameStru);
           compileGraphsPDF(graphMat,tempFileName,outpath);
           close all;
           
           inStru.caseDecomp='single';
           inStru.orgBy='shocks';
           inStru.extract=report.stateDecomp;
           graphMat=shockContributions(inStru,tempKFStru,tempSampleStru,[],nameStru);
           tempFileName=['States Contrib ',char(tempString)];
           compileGraphsPDF(graphMat,tempFileName,outpath);
           close all; 
            

            %%
%             inStru.caseDecomp='single';
%             inStru.orgBy='shocks';
%             tempFileName=strcat('Decomp States Except',char(tempString));
%             graphMat=DecompSeries([],funcmod,parMode,solveopt,addsol,inStru,tempKFStru,...
%                 tempSampleStru,[],nameStru);
%             compileGraphsPDF(graphMat,tempFileName,outpath);

            
        end
    end
end 
clear graphMat inStru temp* NSub; 

%% 8. Only for CEFJ 
rootClean=regexprep(root,'\',''); 
rootClean=regexprep(rootClean,'/',''); 
if strcmp(rootClean,'CEFJ')==true 
    clear temp*; 
    disp('Graphs for CEFJ Project Only') 
    figHand=zeros(2,1); 
    figHand(1)=figure; 
    tempExtract={'FFR','FFR Non-Systematic','FFR Systematic'}; 
    tempPos=cellposition( tempExtract,nameStru.stateNames); 
    FFRMat=KFStru.smoothSt(:,tempPos); 
    comparemat(FFRMat(:,1),sum(FFRMat(:,[2 3]),2)); 
    %tempFFRSS=CONS(tempPos(1),1); 
    %FFRMat=4*( FFRMat+tempFFRSS*ones(size(FFRMat)) ); 
    subplot(2,1,1); 
    tempStru.legend=tempExtract(1:2);
    tempStru.xOffset=0.05;
    tempStru.yOffset=0.05;
    tempStru.legendLocation='best';
    tempStru.flagBoxOff=1; 

    %tempStru.title={'FFR Actual and Non-Systematic Component'}; 
    tempStru=plotAssignDefaults(tempStru); 
        plot3sampSub(sampleSS.sampleVec,FFRMat(:,[1 2]),...
        'FFR Actual and Non-Systematic Component',1,tempStru); 
        hHandle=hline(0); 
    set(hHandle,'Color',[0 0 1],'LineStyle',':','LineWidth',1.5); 

    subplot(2,1,2);
    tempStru.legend=tempExtract([1 3]);
    tempStru=plotAssignDefaults(tempStru);
    %tempStru.subtitle='In deviations from SS, quarterly rates';
    plot3sampSub(sampleSS.sampleVec,FFRMat(:,[1 3]),...
        'FFR Actual and Systematic Component',1,tempStru);
    hHandle=hline(0); 
    set(hHandle,'Color',[0 0 1],'LineStyle',':','LineWidth',1.5); 
    set(figHand(1),'PaperPosition',[0.75 0.5 7.5 10]);

    tempStru.legend=tempExtract;
    tempStru.flagLandscape=0;
    tempStru.lineStyles={'-','--','-'};
    tempStru.markers={'none','none','*'};
    tempStru.markersSize=[0.1,0.1,5];
    tempStru.colors=[0 0 0;0 0 0;0.5 0.5 0.5];
    figHand(2)=figure; 
    plot3sampSub(sampleSS.sampleVec,FFRMat,...
        'FFR Decomposition',1,tempStru);
    hHandle=hline(0);    
    set(hHandle,'Color',[0 0 1],'LineStyle',':','LineWidth',1.5);
    
    set(figHand(2),'PaperOrientation','Landscape') 
    set(figHand(2),'PaperPosition',[0.2 0.1 10.5 8.3]);
    
    cd(cucd); 
    
    compileGraphsPDF(figHand,'FFR Decomposition',outpath);
    clear temp* FFRMat figHand;     
    cd(cucd); 
    
end 

% Recall POS_DECOMPSTATES and DECOMPSTATES_NAMES are different from ZNAMES
% and POS_OBSINSTATES in that they adjust to plot the cummulators at the
% end
% close all;
% deleteFile('Decomposition by Series.ps',outpath); 
% graphStru.mode='cols';          
% graphStru.legend={'Data','CounterFactual'} ;          
% graphStru.xaxis=sample; 
% graphStru.colNames=nameStru.obsNames; 
% nameStru.pageNames=nameStru.shockNames; 
% plotColsOrPages(Ydem,KFStru.countObs,junkStru,nameStru)

 
 
%%

% Ydem=demeanDSGEY(Y,funcmod,parmode_top,solveopt,addsol);
% subSample=2000.00:2005.00; 
% posSubSample=(find( sample==subSample(1) ):find( sample==subSample(end) ));
% fakeSample.sampleVec=sample(posSubSample); 
% graphStru.NYears=6; 
% for ii=1:length(nameStru.obsNames);
%     graphStru.suptitle=nameStru.obsNames(ii);
%     figsHandle=plotDecompPerSeries(Ydem(posSubSample,ii),squeeze(KFStru.countObs(posSubSample,ii,:)),...
%         fakeSample,graphStru,nameStru);
%     cd(outpath);
%     for jj=1:length(figsHandle);
%         if ii== 1 && jj==1 
%             print(figsHandle(jj),'-dpsc','Decomposition by Series SubSamp');
%         else
%             print(figsHandle(jj),'-dpsc','Decomposition by Series SubSamp','-append');
%         end
%     end
% cd(cucd); 
% end

 

% %% Plot per shock 
% %pospershock=cellposition({'unemployment','finding','separation','vacancies','gdp','I','C'},stanames); 
% pospershock=cellposition(znames,stanames); 
% 
% %% Decomposition with Neutral and MEI shocks only 
% % [figvec_zphi,decmat_zphi,vrat_zphi]=plot_decompositions_pergroup_mixfreq(smooth_st(:,pos_decompstates),countmat(:,pos_decompstates,:),decompstates_names,shonames,{'Neutral technology','MEI'},'Neutral and MEI shocks only',0.1,0,indecomp);
% % cd(outpath);
% % print(figvec_zphi,'-dpdf','Neutral MEI only');
% % cd(cucd);
% 
% 
% 
% 
% %% Decomposition with all but measurement errors
% 
% % [figvec_nome,decmat_nome,vrat_nome]=plot_decompositions_pergroup_mixfreq(smooth_st(:,pos_decompstates),countmat(:,pos_decompstates,:),decompstates_names,shonames,{'Neutral technology','MEI','Job destruction','Discount factor','Aggregate demand','Matching'},'All but measurement errors',0.1,0,indecomp);
% % 
% % indecomp.decompmat_zphi=decmat_zphi; 
% % indecomp.vratio_zphi =vrat_zphi; 
% % indecomp.decompnames=decompstates_names; 
% % indecomp.label_zphi={'Neutral & MEI Only'}; 
% % indecomp.actual    =smooth_st(:,pos_decompstates); 
% % indecomp.vratio_nome=vrat_nome; 
% % 
% % cd(outpath);
% % print(figvec_zphi,'-dpdf','All but Measurement errors');
% % save counterfactuals indecomp smooth_st pos_decompstates countmat; 
% % cd(cucd);
% 
% 
% figvec=plot_decompositions_pershock(smooth_st(:,pospershock),countmat(:,pospershock,:),stanames(pospershock),shonames,sample,[znames{ii},': decomposition per shock'],0.2,0);
% cd(outpath); 
% for ii=1:length(znames);
%     if ii == 1;
%         print(figvec(ii),'-dpsc','decomposition series'); 
%     else
%         print(figvec(ii),'-dpsc','decomposition series','-append'); 
%     end    
% end
% cd(cucd); 

% Create table with the states and innovations 
% cd(outpath); 
% save statemat smooth_st stt stanames shonames etamat; 
% if flagStru_mixfreq==1
%     outputcell = crtcell(smooth_st(:,1:end-out.nzLF),num2cprec(sample),stanames,{'SmoothStates'}); 
% else
%     outputcell = crtcell(smooth_st,num2cprec(sample),stanames,{'Smooth States'}); 
% end
% 
% if ~isunix
%     xlswrite('tab states',outputcell,'SmoothSt');
% else
%     savecell(outputcell,[],outpath,['tab states', '_', 'SmoothSt']);
% end
% if ~isunix
%     xlswrite('tab states',crtcell(etamat,num2cprec(sample),shonames,{'Smooth Innovation'}),'SmoothEta'); 
% else
%     savecell(crtcell(etamat,num2cprec(sample),shonames,{'Smooth Innovation'}), ...
%         [], outpath, ['tab states', '_','SmoothEta']); 
% end
% cd(cucd); 
% 
% %% Plot stochastic shocks and their innovations 
% % Shocks_sel variable must be defined in the Settings.m file 
% if exist('shocks_sel','var')==1 && ~isempty(shocks_sel)
%     stshocks_pos=cellposition(shocks_sel,stanames);
%     figvec=zeros( length(shocks_sel) );
%     for ii=1:length(shocks_sel);
%         figvec(ii)=figure;
%         subplot(2,1,1);
%         plot(sample,smooth_st(:,stshocks_pos(ii)),'LineWidth',2 );
%         title([shocks_sel{ii},': exogenous process'],'FontSize',14);
%         xlim([sample(1) sample(end)+0.1]);
%         nberdates_ajd('y');
%         subplot(2,1,2);
%         plot(sample,etamat(:,ii),'LineWidth',2 );
%         title([shonames{ii},': innovations'],'FontSize',14);
%         xlim([sample(1) sample(end)+0.1]);
%         subtitulo(extrsubf(outpath,cucd));
%     end
%     cd(outpath);
%     for ii=1:length(shocks_sel);
%         if ii == 1;
%             print(figvec(ii),'-dpsc','Shocks');
%         else
%             print(figvec(ii),'-dpsc','Shocks','-append');
%         end
%     end
%     if ~isunix
%         ps2pdf('psfile', 'Shocks.ps', 'pdffile', 'Shocks.pdf', 'deletepsfile',1);
%     end
% end
% cd(cucd); 